<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter  @changeFilter="changeFilter"/>
      <!-- 排序 -->
      <div class="goods-list">
        <SubSort @changeSort="changeSort"/>
        <!-- 商品列表 -->
        <ul>
          <li v-for="good in goodsList" :key="good.id">
            <GoodsItem :good="good" />
          </li>
        </ul>
        <!-- 无限加载组件 -->
        <XtxInfiniteLoading v-model:loading="loading" :finished="finished" @load="onLoad"></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>

<script>
import SubBread from './components/sub-bread'
import SubFilter from './components/sub-filter'
import SubSort from './components/sub-sort'
import GoodsItem from './components/goods-item'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/api/category'
export default {
  name: 'SubCategory',
  components: { SubBread, SubFilter, SubSort, GoodsItem },
  setup () {
    const route = useRoute()
    const check = ref(false)
    const loading = ref(false)
    const finished = ref(false)
    const goodsList = ref([])
    // 查询参数
    let reqParams = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id
    }
    const onLoad = async () => {
      loading.value = true
      // 发送请求 获取商品数据
      const res = await findSubCategoryGoods(reqParams)
      // console.log(res)
      goodsList.value = [...goodsList.value, ...res.result.items]
      reqParams.page++
      // 加载完成一定要把loading改为false
      loading.value = false
      if (res.result.items.length < reqParams.pageSize) {
        // 没有更多数据
        finished.value = true
      }
    }

    const changeSort = (sortParams) => {
      // console.log(sortParams)
      reqParams = {
        ...reqParams,
        ...sortParams
      }
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
      onLoad()
    }

    const changeFilter = (filter) => {
      console.log(filter)
      reqParams = {
        ...reqParams,
        ...filter
      }
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
      onLoad()
    }
    return {
      check,
      loading,
      finished,
      onLoad,
      goodsList,
      changeSort,
      changeFilter
    }
  }
}
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
